import 'dart:io';

import 'package:cgvc/helper/string_helper.dart';
import 'package:cgvc/main.dart';
import 'package:cgvc/util/platform_util.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class ThemeViewModel extends ChangeNotifier {
  static const SP_KEY_THEME_DARK_MODE = 'SP_KEY_THEME_DARK_MODE';
  static const SP_KEY_THEME_COLOR_INDEX = 'SP_KEY_THEME_COLOR_INDEX';
  static const SP_KEY_FONT_INDEX = 'SP_KEY_FONT_INDEX';
  static const SP_KEY_FONT_TEXT_SIZE = 'SP_KEY_FONT_TEXT_SIZE';

  //用户选择的暗色模式
  static bool _userDarkMode = false;
  static bool get userDarkMode => _userDarkMode;
  //手机的深色模式
  static bool get platformDarkMode =>
      navigatorKey.currentContext != null &&
      MediaQuery.of(navigatorKey.currentContext).platformBrightness ==
          Brightness.dark;
  //用户在应用内选择了深色模式或者手机设置了深色模式
  static bool get darkMode => _userDarkMode || platformDarkMode;

  static MaterialColor _themeColor = Colors.blue;
  //强调色
  static Color _accentColor = _themeColor;
  static Color get accentColor => _accentColor;

  static Color get themeAccentColor =>
      _userDarkMode ? colorBlackTheme : _accentColor;

  static const fontValueList = ['system', 'StarCandy'];
  //当前字体
  static int _fontIndex = 0;
  int get fontIndex => _fontIndex;

  static int _themeIndex = 7;
  int get themeIndex => _themeIndex;

  static double _articleTextScaleFactor = 1.0;
  static double get articleTextScaleFactor => _articleTextScaleFactor;

  static double get textScaleFactor => 1;

  static bool _hideFloatingButton = false;
  static bool get hideFloatingButton => _hideFloatingButton;

  static const List<MaterialColor> themeValueList = [
    Colors.red,
    Colors.orange,
    Colors.yellow,
    Colors.green,
    Colors.cyan,
    Colors.blue,
    Colors.purple,
    Colors.pink
  ];

  static Color colorBlackTheme = Colors.grey[900];

  ///构造方法，初始化一些参数
  ThemeViewModel() {
    LogUtil.v('初始化主题设置');
    _userDarkMode = SpUtil.getBool(SP_KEY_THEME_DARK_MODE, defValue: false);
    _themeIndex =
        SpUtil.getInt(SP_KEY_THEME_COLOR_INDEX, defValue: _themeIndex);
    _themeColor = themeValueList[_themeIndex];
    _accentColor = _themeColor;

    //获取本地字体
    _fontIndex = SpUtil.getInt(SP_KEY_FONT_INDEX);

    //获取本地字体缩放
    _articleTextScaleFactor =
        SpUtil.getDouble(SP_KEY_FONT_TEXT_SIZE, defValue: 1.0);

    switchTheme();
  }

  void switchFontTextSize(double textScaleFactor) {
    _articleTextScaleFactor = textScaleFactor;
    switchTheme();
    SpUtil.putDouble(SP_KEY_FONT_TEXT_SIZE, _articleTextScaleFactor);
  }

  void switchTheme(
      {bool userDarkMode, int themeIndex, MaterialColor color}) async {
    if (themeIndex != null && themeIndex != _themeIndex) {
      SpUtil.putInt(SP_KEY_THEME_COLOR_INDEX, themeIndex);
    }
    _userDarkMode = userDarkMode ?? _userDarkMode;
    _themeIndex = themeIndex ?? _themeIndex;
    _themeColor = color ?? getThemeColor();

    //写入缓存
    SpUtil.putBool(SP_KEY_THEME_DARK_MODE, _userDarkMode);
    notifyListeners();
  }

  static MaterialColor getThemeColor({int i}) {
    int index = i ?? _themeIndex;
    //选择主题颜色，当index是themeValueList的最后一个时，按照星期来选择
    return index == themeValueList.length - 1
        ? themeValueList[DateTime.now().weekday - 1]
        : themeValueList[index];
  }

  ///不显示的定义返回值类型，其实返回值是dynamic
  ///根据主题 明暗 和 颜色 生成对应的主题[dark]系统的dark mode
  themeData({bool platformDarkMode: false}) {
    LogUtil.v('themeData-plartformDarkMode: $platformDarkMode');
    var isDrak = platformDarkMode | _userDarkMode;
    var themeColor = _themeColor;
    _accentColor = isDrak ? themeColor[600] : _themeColor;
    Brightness brightness = isDrak ? Brightness.dark : Brightness.light;
    var themeData = ThemeData(
      //主题浅色或深色
      brightness: brightness,
      primaryColorBrightness: brightness,
      accentColorBrightness: brightness,
      primarySwatch: themeColor,

      //强调色
      accentColor: accentColor,
      primaryColor: accentColor,

      //platform,设置了不知道为什么没用
      platform: TargetPlatform.iOS,
      errorColor: Colors.red,
      toggleableActiveColor: accentColor,

      //光标颜色
      cursorColor: accentColor,

      fontFamily: fontValueList[_fontIndex],
    );

    //copyWith,在原来的对象已经赋值了的属性上，可以添加新的属性，新属性是可以覆盖旧属性值的
    themeData = themeData.copyWith(
      cupertinoOverrideTheme: CupertinoThemeData(primaryColor: themeColor),

      //主题设置Appbar样式背景
      appBarTheme: themeData.appBarTheme.copyWith(
        //根据主题设置Appbar样式背景
        color: isDrak ? colorBlackTheme : Colors.white,
        //去掉阴影
        elevation: 0,
        textTheme: TextTheme(
          //title Text样式，原title 被废弃
          headline6: TextStyle(
            color: isDrak ? Colors.white : accentColor,
            fontSize: 17,
            fontWeight: FontWeight.w500,

            //字体
            fontFamily: fontValueList[_fontIndex],
          ),

          //action及leading Text样式，原body1废弃
          bodyText2: TextStyle(
            color: isDrak ? Colors.white : accentColor,
            fontSize: 10,
            fontWeight: FontWeight.w500,
            fontFamily: fontValueList[_fontIndex],
          ),
        ),

        //appbar的icon主题
        iconTheme: IconThemeData(
          color: isDrak ? Colors.white : accentColor,
        ),
      ),

      //应用的icon主题设置
      iconTheme: themeData.iconTheme.copyWith(color: accentColor),

      //水波纹
      splashColor: themeColor.withAlpha(50),

      tooltipTheme: themeData.tooltipTheme.copyWith(
        textStyle: TextStyle(
            fontSize: 13,
            color: (darkMode ? Colors.black : Colors.white)
                .withOpacity(0.9)), //withOpacity不透明度
      ),

      //tabbar的样式
      tabBarTheme: themeData.tabBarTheme.copyWith(
        //标签内边距，横向对称
        labelPadding: EdgeInsets.symmetric(horizontal: 8),

        //选中文本样式
        labelStyle: TextStyle(
          fontWeight: FontWeight.w600,
          fontSize: 14,
          fontFamily: fontValueList[_fontIndex],
        ),

        //未选中文本样式
        unselectedLabelStyle: TextStyle(
          fontWeight: FontWeight.normal,
          fontSize: 13,
          fontFamily: fontValueList[_fontIndex],
        ),
      ),

      //悬浮按钮样式
      floatingActionButtonTheme: themeData.floatingActionButtonTheme
          .copyWith(backgroundColor: themeAccentColor),

      //好像没起作用？
      platform: TargetPlatform.iOS,

      dialogTheme: DialogTheme(
        titleTextStyle: TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.w900,
        ),
        contentTextStyle: themeData.textTheme.subtitle1.copyWith(
          fontSize: 14,
        ),
      ),
    );
    setSystemBarTheme();
    return themeData;
  }

  ///设置系统bar主题
  static Future setSystemBarTheme() async {
    LogUtil.v('platformDarkMode:$platformDarkMode; userDarkMode:$userDarkMode');
    bool statusEnable =
        Platform.isAndroid ? await PlatformUtil.isStatusColorChange() : true;

    bool navigationEnable = Platform.isAndroid
        ? await PlatformUtil.isNavigationColorChange()
        : true;

    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      //设置状态栏颜色
      statusBarColor: darkMode || statusEnable ? Colors.transparent : null,

      //状态栏图标颜色
      statusBarIconBrightness: darkMode ? Brightness.light : Brightness.dark,

      systemNavigationBarColor: darkMode
          ? colorBlackTheme
          : navigationEnable
              ? Colors.transparent
              : null,

      //导航栏icon颜色
      systemNavigationBarIconBrightness:
          darkMode ? Brightness.light : Brightness.dark,
    ));
  }

  static String fontFamily() {
    return fontValueList[_fontIndex];
  }

  static String themeName({int i}) {
    int index = i ?? _themeColor;
    switch (index) {
      case 0:
        return StringHelper.getS().red;
      case 1:
        return StringHelper.getS().orange;
      case 2:
        return StringHelper.getS().yellow;
      case 3:
        return StringHelper.getS().green;
      case 4:
        return StringHelper.getS().cyan;
      case 5:
        return StringHelper.getS().blue;
      case 6:
        return StringHelper.getS().purple;
      case 7:
        return '${getWeekStr()}-${themeName(i: DateTime.now().weekday - 1)}';
      default:
        return '';
    }
  }

  static String getWeekStr() {
    int week = DateTime.now().weekday;
    switch (week) {
      case 1:
        return StringHelper.getS().monday;
      case 2:
        return StringHelper.getS().tuesday;
      case 3:
        return StringHelper.getS().wednesday;
      case 4:
        return StringHelper.getS().thursday;
      case 5:
        return StringHelper.getS().friday;
      case 6:
        return StringHelper.getS().saturday;
      case 7:
        return StringHelper.getS().sunday;
      default:
        return '';
    }
  }
}
